<?php

namespace app\admin\controller\shop\user;

use app\admin\controller\shop\Base;
use app\shop\enums\user\UserMoneyChangeType;
use app\shop\service\LogService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use Throwable;

/**
 * 用户管理
 */
class User extends Base
{
    /**
     * User模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\user\User
     */
    protected object $model;

    protected array|string $preExcludeFields = [];

    protected string|array $quickSearchField = ['nickname'];

    protected array $withJoinTable = ['distributiongrade'];

    protected bool $modelSceneValidate = true;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\user\User;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit)
            ->each(function ($item) {
                $item->mobile = substr_replace($item->mobile, '****', 3, -4);

                if($item->pid > 0){
                    $item->pidname = $this->model->where('id',$item->pid)->value('nickname');
                }else{
                    $item->pidname = '';
                }
            });
        $res->visible(['distributiongrade' => ['name']]);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }
        if(isset($row['terminate_time'])){
            $row['terminate_time'] = date('Y-m-d', $row['terminate_time']);
        }
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                if(isset($data['terminate_time'])){
                    $data['terminate_time'] = strtotime($data['terminate_time']);
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * 调整余额
     * @return void
     */
    public function editBalance(): void
    {
        $params = $this->request->post();

        try {
            (new \app\admin\validate\shop\user\User())->scene('edit_balance')->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        try {
            LogService::userMoneyLog($params['user_id'], $params['money'], $params['memo'], UserMoneyChangeType::SYSTEM_OPERATE);
        } catch (Throwable $e) {
            $this->error('余额调整失败,请刷新重试', ['err' => $e->getMessage()]);
        }

        $this->success('调整成功');
    }
}